package io.gitee.hchaojie.day04;

import org.junit.Test;

import java.util.Arrays;
import java.util.Comparator;

public class DemoComparator {
    @Test
    public void test() {
        String[] array = {"hello", "world", "java", "animal"};

        Arrays.sort(array);     // 字符串的字母序
        
        System.out.println(Arrays.toString(array));
    }

    // 按字符串长度排序
    @Test
    public void test2() {
        String[] array = {"hello", "world", "java", "animal"};

        // Arrays.sort(array, array)
        Arrays.sort(array, new LengthComparator());

        System.out.println(Arrays.toString(array));
        
        Arrays.sort(array, new LengthDescComparator());
        System.out.println(Arrays.toString(array));
    }
}

// <String> 泛型，代表比较的每个元素的类型
class LengthComparator implements Comparator<String> {
    // 如果o1 > o2, 返回一个1
    // o1 == o2, 返回0
    // o1 < o2, 返回-1

    @Override
    public int compare(String o1, String o2) {
        return o1.length() - o2.length();

//        if (o1.length() > o2.length()) {
//            return 1;
//        } else if (o1.length() == o2.length()) {
//            return 0;
//        } else {
//            return -1;
//        }
    }
}

class LengthDescComparator implements Comparator<String> {
    @Override
    public int compare(String o1, String o2) {
        return o2.length() - o1.length();
    }
}
